package cn.insect.servlet;

import cn.insect.pojo.Insect;
import cn.insect.service.InsectService;
import cn.insect.service.impl.InsectServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @auth 吴阳基
 * @date 2024/1/3 18:58
 */
@WebServlet(urlPatterns = "/add")
public class Add extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");

        InsectService insectService = new InsectServiceImpl();
        Insect insect = new Insect();
        insect.setName(req.getParameter("name"));
        insect.setLife(Integer.valueOf(req.getParameter("life")));
        insect.setArea(req.getParameter("area"));
        insect.setDiscovery_time(req.getParameter("time"));
        insect.setCid(Integer.valueOf(req.getParameter("cid")));

        int result = insectService.add(insect);
        PrintWriter out = resp.getWriter();

        if (result>0){
            out.println("<script>alert(\"添加成功！\");location.href=\"select\";</script>");
        }else {
            out.println("<script>alert(\"添加失败！\");history.back();</script>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
